package com.itqf;

import com.alibaba.fastjson.JSON;
import com.itqf.entity.User;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/3/4
 * @Time: 下午4:19
 */
public class TestRedisUse {

    public List<User> findAll(){

        //1.redis
        Jedis jedis = new Jedis("192.168.82.168",6379);
        jedis.auth("jbgsn");
        //2.从redis中取数据
        String key = "adduser";
        List<User> userList  = new ArrayList<>();
        List<String> list = jedis.lrange(key,0,-1);
        if (list!=null&&list.size()>0){
            System.out.println("--->走redis");

            for (int i = 0; i < list.size(); i++) {
                userList.add(JSON.parseObject(list.get(i),User.class));
            }
        }else{
            // //数据库
            System.out.println("---->走数据库");
            for (int i = 0; i < 10; i++) {
                userList.add(new User((i+1),"admin"+i,new Date()));
            }
            //存到redis缓存中
            //同步数据到redis中
            for (User user : userList) {
                jedis.rpush(key,JSON.toJSONString(user));
            }
        }

        return  userList;


    }

    public  static  void  main(String[]args){

        TestRedisUse use = new TestRedisUse();
        for (int i = 0; i < 10; i++) {
            System.out.println(use.findAll());
        }


    }


}
